package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中token
        String token = request.getHeader("Authorization");

        //2.当token不为空的时候,去redis中获取下数据
        if (StrUtil.isNotBlank(token)) {
            //3.当获取的数据不为空的时候,转成user
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String jsonStr = operations.get(ConstantUtil.USER_TOKEN + token);

            if (StrUtil.isNotBlank(jsonStr)) {
                User user = JSON.parseObject(jsonStr, User.class);

                //4.将用户存入当前线程中
                UserHolder.set(user);

                //5.为了防止失效,需要重置30天(续期)且放行
                operations.set(ConstantUtil.USER_TOKEN+token,jsonStr, Duration.ofDays(30));

                return true;
            }
        }
        //6.上面任何一个不满足,返回401
        response.setStatus(401);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //将用户和当前线程解绑
        UserHolder.remove();
    }
}
